<template>
  <div class="search-result">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <van-cell
        v-for="(text, index) in list"
        :key="index"
        :title="text.title"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search'
export default {
  name: 'SearchResult',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      page: 1,
      perPage: 10,
      error: false
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onLoad() {
      try {
        // 1.请求获取数据
        const { data } = await getSearchResult({
          page: this.page, // 页码
          per_page: this.perPage, // 每页数量
          q: this.searchText // 搜索关键词
        })
        console.log('搜索结果', data)
        // 测试失败
        // if (Math.random() > 0.5) {
        //   JSON.parse('dfsgr')
        // }
        // 2.将数据添加到数组中
        const { results } = data.data
        this.list.push(...results)
        // 3.将本次加载中的 loading 改为 false
        this.loading = false
        // 4.判断是否还有数据
        if (results.length) {
          this.page++
        } else {
          // 5.没有数据 finished 设置为 true
          this.finished = true
        }
      } catch (error) {
        // 加载失败，提示状态
        this.error = true
        // loading 加载状态关闭
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-result {
  // 滚动条禁止顶到顶部
  height: 92vh;
  overflow: scroll;
}
</style>
